package com.hmall.search.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.search.mapper.SearchMapper;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description SearchServiceImpl
 * @Author GGBond
 * @Date 2024-11-15
 */
@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Item> implements SearchService {

    @Autowired
    private SearchMapper searchMapper;

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;


    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        //创建请求
        SearchRequest request = new SearchRequest("item");

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //设置请求参数
        //查询关键字
        if (StrUtil.isBlank(params.getKey())) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", params.getKey()));
        }

        //查询品牌
        if (StrUtil.isNotBlank(params.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }

        //查询分类
        if (StrUtil.isNotBlank(params.getCategory())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }

        //价格过滤
        if (params.getMaxPrice() != null && params.getMinPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));
        }

        request.source().query(boolQueryBuilder);

        //排序
        if ("销量".equals(params.getSortBy())) {
            request.source().sort("sold");
        }
        if ("价格".equals(params.getSortBy())) {
            request.source().sort("price");
        }

        //分页
        int from = (params.getPage() - 1) * params.getSize();
        request.source().from(from).size(params.getSize());

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name").preTags("<em>").postTags("</em>").requireFieldMatch(false);
        request.source().highlighter(highlightBuilder);

        //竞价排名
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10))
                });

        functionScoreQueryBuilder.boostMode(CombineFunction.SUM);

        request.source().query(functionScoreQueryBuilder);

        //对结果进行解析
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long total = hits.getTotalHits().value;
            SearchHit[] searchHits = hits.getHits();
            List<ItemDoc> itemDocList = new ArrayList<>();
            if (searchHits != null && searchHits.length > 0) {
                for (SearchHit searchHit : searchHits) {
                    String sourceAsString = searchHit.getSourceAsString();
                    ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
                    //获取高亮字段
                    HighlightField highlightField = searchHit.getHighlightFields().get("name");
                    if (ObjectUtil.isNotEmpty(highlightField)) {
                        String string = highlightField.getFragments()[0].string();
                        //替换高亮字段
                        itemDoc.setName(string);
                    }
                    itemDocList.add(itemDoc);
                }
            }
            PageDTO<ItemDoc> pageDTO = new PageDTO<>();
            pageDTO.setTotal(total);
            pageDTO.setList(itemDocList);
            return pageDTO;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
